package rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author: DRevelation
 * @Date: 2021/4/28 14:43
 */
public class ConsumerDemo {

    private static final String IP_ADDRESS = "127.0.0.1";
    private static final Integer PORT = 5672;
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "111111";

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP_ADDRESS);
        factory.setPort(PORT);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);

        try (Connection conn = factory.newConnection(); Channel channel = conn.createChannel()) {
            channel.basicQos(64);

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    // 打印日志
                    System.out.printf("[线程：%s][路由键：%s][消息内容：%s]%n",
                            Thread.currentThread(), envelope.getRoutingKey(), new String(body));
                    // ack 消息已经消费
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            channel.basicConsume("queue-01", consumer);
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
